import 'package:hinge/common/models/topic_model.dart';
import 'package:hinge/common/models/topic_comment_model.dart';
import 'package:hinge/common/services/user_service.dart';
import 'package:hinge/common/utils/sp_util.dart';
import 'dart:math' as math;

/// 话题服务类 - 管理话题数据
class TopicService {
  // 存储键名
  static const String topicsStorageKey = 'app_topics';

  // 初始化默认话题数据
  static Future<void> initDefaultTopics() async {
    // 检查是否已有数据
    final existingTopics = getAllTopics();
    if (existingTopics.isNotEmpty) {
      return; // 已有数据，不再初始化
    }

    // 默认话题数据
    final List<TopicModel> defaultTopics = [
      TopicModel(
        id: 1,
        question: 'Where do some perfume designs and inspirations come from?',
        percentage: 45.0,
        comments: [],
      ),
      TopicModel(
        id: 2,
        question: 'Any recommendations for fragrances that soothe your nerves?',
        percentage: 30.0,
        comments: [],
      ),
      TopicModel(
        id: 3,
        question: 'What happens to the smell of perfume when it expires?',
        percentage: 20.0,
        comments: [],
      ),
      TopicModel(
        id: 4,
        question: 'Which perfumes are worth collecting?',
        percentage: 35.0,
        comments: [],
      ),
      TopicModel(
        id: 5,
        question: 'Who are some of the world-famous perfumers?',
        percentage: 40.0,
        comments: [],
      ),
    ];

    // 保存到本地存储
    await SpUtil.setModelList(
      topicsStorageKey,
      defaultTopics.map((topic) => topic.toJson()).toList(),
    );
  }

  // 获取所有话题
  static List<TopicModel> getAllTopics() {
    return SpUtil.getModelList(
      topicsStorageKey,
      (json) => TopicModel.fromJson(json),
    );
  }

  // 根据ID获取话题
  static TopicModel? getTopicById(int topicId) {
    try {
      return getAllTopics().firstWhere((topic) => topic.id == topicId);
    } catch (e) {
      return null;
    }
  }

  // 添加新话题
  static Future<TopicModel> addTopic(String question, double percentage) async {
    // 获取现有话题
    final topics = getAllTopics();

    // 生成新ID
    int newId =
        topics.isEmpty ? 1 : topics.map((e) => e.id).reduce(math.max) + 1;

    // 创建新话题
    final newTopic = TopicModel(
      id: newId,
      question: question,
      percentage: percentage,
      comments: [],
    );

    // 添加到列表
    topics.add(newTopic);

    // 保存更新后的列表
    await SpUtil.setModelList(
      topicsStorageKey,
      topics.map((topic) => topic.toJson()).toList(),
    );

    return newTopic;
  }

  // 更新话题
  static Future<bool> updateTopic(TopicModel updatedTopic) async {
    final topics = getAllTopics();
    int index = topics.indexWhere((topic) => topic.id == updatedTopic.id);

    if (index != -1) {
      topics[index] = updatedTopic;

      // 保存更新后的列表
      await SpUtil.setModelList(
        topicsStorageKey,
        topics.map((topic) => topic.toJson()).toList(),
      );

      return true;
    }
    return false;
  }

  // 删除话题
  static Future<bool> deleteTopic(int topicId) async {
    final topics = getAllTopics();
    int initialLength = topics.length;

    topics.removeWhere((topic) => topic.id == topicId);

    if (topics.length < initialLength) {
      // 保存更新后的列表
      await SpUtil.setModelList(
        topicsStorageKey,
        topics.map((topic) => topic.toJson()).toList(),
      );
      return true;
    }

    return false;
  }

  // 为话题添加评论
  static Future<TopicCommentModel> addComment(
    int topicId,
    int userId,
    String content,
  ) async {
    // 获取话题
    final topics = getAllTopics();
    int topicIndex = topics.indexWhere((topic) => topic.id == topicId);

    if (topicIndex == -1) {
      throw Exception('Topic with ID $topicId not found');
    }

    // 生成评论ID
    List<TopicCommentModel> existingComments = topics[topicIndex].comments;
    int newCommentId =
        existingComments.isEmpty
            ? 1
            : existingComments.map((e) => e.id).reduce(math.max) + 1;

    // 创建评论
    final newComment = TopicCommentModel(
      id: newCommentId,
      topicId: topicId,
      userId: userId,
      user: UserService.getUserById(userId),
      timestamp: DateTime.now(),
      content: content,
    );

    // 更新话题评论列表
    topics[topicIndex] = topics[topicIndex].copyWith(
      comments: [...existingComments, newComment],
    );

    // 保存更新后的列表
    await SpUtil.setModelList(
      topicsStorageKey,
      topics.map((topic) => topic.toJson()).toList(),
    );

    return newComment;
  }

  // 获取话题评论
  static List<TopicCommentModel> getCommentsByTopicId(int topicId) {
    final topic = getTopicById(topicId);
    return topic?.comments ?? [];
  }
}
